# /usr/bin/python
# -*- coding: utf-8 -*-

import os,sys
import time,datetime
BASE_DIR = os.path.dirname(os.path.abspath(os.curdir))
sys.path.append(BASE_DIR)
reload(sys)  
sys.setdefaultencoding('utf8')   
from models.Zabbix import ZBX
from models.MySQL import MySQL
from util.log import get_stream_logger

logger = get_stream_logger("add_hosts_group")

with MySQL() as cur:
    cmd = "SELECT SvrId,HGId FROM server_hostgroup_relation"
    relations = cur.search(cmd)

for relation in relations:
    with MySQL() as cur:
        try:
            server_cmd = "SELECT SvrId,SvrName,SvrLanIP FROM server WHERE SvrId='{id}'".format(id=relation[0])
            server_info = cur.search(server_cmd)[0]
            group_cmd = "SELECT HGNAME,HGId FROM server_hostgroup WHERE HGId='{id}'".format(id=relation[1])
            group_info = cur.search(group_cmd)[0]
        except Exception:
            logger.error(relation)
    
    serer_name = server_info[1]
    server_ip = server_info[2]

    group_name = group_info[0]

    with MySQL() as cur:
        server_id_cmd = "SELECT id from host WHERE  hostname='%s' AND ip='%s'"%(serer_name,server_ip)
        res = cur.search(server_id_cmd)
        if len(res) != 1 :
            logger.error("host %s does not exist"%serer_name)
            continue
        server_id = res[0][0]

        group_id_cmd = "SELECT id from grp WHERE grp_name='%s'"%group_name
        res = cur.search(group_id_cmd)
        if len(res) != 1 :
            logger.error("group %s does not exist"%group_name)
            continue

        group_id = res[0][0]

        check_cmd = "SELECT * from grp_host WHERE grp_id='{grp_id}' AND host_id='{host_id}'".format(grp_id=group_id,host_id=server_id)   
        check_res = cur.cur.execute(check_cmd)
        if check_res == 0:
            insert_cmd = "INSERT INTO grp_host VALUES ('{grp_id}','{host_id}')".format(grp_id=group_id,host_id=server_id) 
            insert_res = cur.update(insert_cmd)
            if insert_res != 1:
                logger.error("Insert into grp_host failed, host:{host_id}, group:{group_ud}",format(host_id=server_id,group_id=group_id))        
